﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Pages_Connection : System.Web.UI.Page
{

    int ConnectionId
    {
        get
        {
            if (Request.QueryString["ConnectionId"] != null)
            {
                return Convert.ToInt32(Request.QueryString["ConnectionId"]);
            }
            else
            {
                return 0;
            }

        }
    }

    int UserId
    {
        get
        {
            if (Session["user"] != null && Session["user"].ToString() == "DEMO")
            {
                return 1;
            }
            else
            {
                return 0;
            }

        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetContentHeader();
            if (ConnectionId != 0)
            {
                DBCDS.ConnectionRow cRow = new DBCDSTableAdapters.ConnectionTableAdapter().GetDataById(ConnectionId).First();
                txtConnectionName.Text = cRow.ConnectionName;
                txtConnectionString.Text = cRow.ConnectionString;
            }
            txtConnectionName.Focus();
        }
    }

    protected void btnTest_Click(object sender, EventArgs e)
    {
        try
        {
            lblMessage.Text = string.Empty;
            imgOK.Visible = false;

            SqlConnection conn = new SqlConnection(txtConnectionString.Text);
            conn.Open();
            conn.Close();
            imgOK.Visible = true;
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (ConnectionId == 0)
        {
            new DBCDSTableAdapters.ConnectionTableAdapter().Insert(
                txtConnectionName.Text,
                txtConnectionString.Text,
                UserId);
        }
        else
        {
            new DBCDSTableAdapters.ConnectionTableAdapter().Update(
                           txtConnectionName.Text,
                           txtConnectionString.Text,
                           UserId,
                           ConnectionId);
        }

        Response.Redirect("ConnectionList.aspx");
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        new DBCDSTableAdapters.ConnectionTableAdapter().Delete(ConnectionId);
        Response.Redirect("ConnectionList.aspx");
    }

    private void SetContentHeader()
    {
        OutlookMaster om = (OutlookMaster)Master;
        om.ContentHeader.Text = "Connection";
    }
}